package com.tbr.blockchain.p2p;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * p2p客户端
 *
 */
@Component("p2pClient")
public class P2PClient {
    //所有客户端WebSocket的连接池
    @Resource
   private P2PService p2pService;

    @Value("${P2P_CLIENT_PEER}")
    private String P2P_CLIENT_PEER;

    public P2PClient(P2PService p2pService){
        this.p2pService=p2pService;
    }

    /**
     * 连接到peer
     */
    public void connectPeer() {
        try {
            if("".equals(P2P_CLIENT_PEER)) {
                return;
            }

            final WebSocketClient socketClient = new WebSocketClient(new URI(P2P_CLIENT_PEER)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    p2pService.write(this,p2pService.queryLatestBlockMsg());
                    p2pService.write(this,p2pService.queryTransactionMsg());
                    p2pService.write(this,p2pService.queryPackedTransactionMsg());
                    p2pService.write(this,p2pService.queryWalletMsg());
                    p2pService.getSockets().add(this);
                }

                @Override
                public void onMessage(String msg) {
                    p2pService.handleMessage(this, msg, p2pService.getSockets());
                }

                @Override
                public void onClose(int i, String msg, boolean b) {
                    System.out.println("客户端关闭");
                    p2pService.getSockets().remove(this);
                }

                @Override
                public void onError(Exception e) {
                    System.out.println(e.getMessage());
                    System.out.println("客户端报错");
                    p2pService.getSockets().remove(this);
                }
            };
            //客户端 开始连接服务端
            socketClient.connect();
        } catch (URISyntaxException e) {
            System.out.println("连接错误:" + e.getMessage());
        }
    }
    /**
     * 向服务端发送消息
     * 当前WebSocket的远程Socket地址，就是服务器端
     * @param ws：
     * @param message
     */
    public void write(WebSocket ws, String message) {
        System.out.println("发送给" + ws.getRemoteSocketAddress().getPort() + "的p2p消息:" + message);
        ws.send(message);
    }
    /**
     * 向所有服务端广播消息
     * @param message
     */
    public void broatcast(String message) {
        if (p2pService.getSockets().size() == 0) {
            return;
        }
        System.out.println("======广播消息开始：");
        for (WebSocket socket : p2pService.getSockets()) {
            this.write(socket, message);
        }
        System.out.println("======广播消息结束");
    }
}
